package com.nwcl.basic.service.impl;

import com.nwcl.basic.bo.UserIntegralBO;
import com.nwcl.basic.dao.UserIntegralDao;
import com.nwcl.basic.dao.UserIntegralFlowDao;
import com.nwcl.basic.entity.UserIntegral;
import com.nwcl.basic.entity.UserIntegralFlow;
import com.nwcl.basic.service.UserIntegralService;
import com.nwcl.common.constant.Constant;
import com.nwcl.common.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author liguiqin
 * @date 2023/5/23
 */
@Service
public class UserIntegralServiceImpl implements UserIntegralService {
    @Autowired
    private UserIntegralDao userIntegralDao;
    @Autowired
    private UserIntegralFlowDao userIntegralFlowDao;

    @Override
    public BigDecimal getIntegralByUser(Integer userId) {
        BigDecimal integral = userIntegralDao.getIntegralByUserAndTime(userId, new Date());
        return integral != null ? integral : new BigDecimal(0);
    }

    @Override
    public void deduction(Integer userId, BigDecimal integral, Integer orderId) {
        List<UserIntegral> list = userIntegralDao.listIntegralByUserAndTime(userId, new Date());
        for (UserIntegral model : list) {
            //如果用户积分大于等于商品积分
            if (model.getIntegral().compareTo(integral) >= 0) {
                BigDecimal userIntegral = model.getIntegral().subtract(integral);
                userIntegralDao.updateIntegralById(model.getId(), userIntegral);
                break;
            }
            //积分不足,逐条扣除
            integral = integral.subtract(model.getIntegral());
            userIntegralDao.updateIntegralById(model.getId(), new BigDecimal(0));
        }
        //新增积分流水记录
        UserIntegralFlow flow=new UserIntegralFlow();
        flow.setUserId(userId);
        flow.setType(Constant.UserIntegralFlowType.sub);
        flow.setBusinessType(Constant.UserIntegralFlowBusinessType.cash);
        flow.setIntegral(integral);
        flow.setOrderId(orderId);
        flow.setCreateTime(new Date());
        flow.setUpdateTime(new Date());
        flow.setIsValid(Constant.isValid.valid);
        userIntegralFlowDao.save(flow);
    }

    @Override
    public void save(UserIntegralBO userIntegralBO) {
        UserIntegral integral= BeanUtil.copy(userIntegralBO,UserIntegral.class);
        userIntegralDao.save(integral);
    }
}
